import 'dart:convert';

import 'package:flutter/material.dart';
import 'package:shared_preferences/shared_preferences.dart';

import '../main.dart';
import '../models/user_model.dart';
import '../utils/http_client.dart';
import 'home_screen.dart';

class LoginScreen extends StatefulWidget {
  String? version;
  // bool? needUpdate;
  LoginScreen({
    super.key,
    // this.needUpdate,
    this.version
  });

  @override
  State<LoginScreen> createState() => _LoginScreenState();
}

class _LoginScreenState extends State<LoginScreen> {
  final _formKey = GlobalKey<FormState>();
  final _employeeIdController = TextEditingController();
  final _passwordController = TextEditingController();
  bool _isPasswordVisible = false;
  bool _autoLogin = true;

  @override
  void initState() {
    super.initState();
    _checkAutoLogin();
  }

  Future<void> _checkAutoLogin() async {
    final prefs = await SharedPreferences.getInstance();
    final savedJobNumber = prefs.getString('savedJobNumber');
    final savedPassword = prefs.getString('savedPassword');
    final autoLogin = prefs.getBool('autoLogin') ?? true;
    final loginTimeStr = prefs.getString('loginTime');

    if (savedJobNumber != null && savedPassword != null && autoLogin && loginTimeStr != null) {
      final loginTime = DateTime.parse(loginTimeStr);
      final now = DateTime.now();
      final difference = now.difference(loginTime);

      if (difference.inDays < 30) {
        _employeeIdController.text = savedJobNumber;
        _passwordController.text = savedPassword;
        setState(() {
          _autoLogin = true;
        });
        // if(!widget.needUpdate!){
          _login();
        // }
      } else {
        await prefs.remove('savedJobNumber');
        await prefs.remove('savedPassword');
        await prefs.remove('loginTime');
      }
    }
  }


  Future<void> _login() async {
    if (_formKey.currentState!.validate()) {
      try {
        final response = await HttpClient.dio.post(
          '/main/login',
          data: {
            'jobNumber': _employeeIdController.text,
            'password': _passwordController.text,
          },
        );
        if (response.data['code'] == 0) {
          var d = response.data['data'];
          // 保存登录信息
          final prefs = await SharedPreferences.getInstance();

          if (_autoLogin) {
            final loginTime = DateTime.now();
            await prefs.setString('savedJobNumber', _employeeIdController.text);
            await prefs.setString('savedPassword', _passwordController.text);
            await prefs.setString('loginTime', loginTime.toIso8601String());
            await prefs.setBool('autoLogin', _autoLogin);
          } else {
            await prefs.remove('savedJobNumber');
            await prefs.remove('savedPassword');
            await prefs.remove('loginTime');
          }

          // 保存用户信息
          final userInfo = UserModel.fromJson(d);
          await prefs.setString('userInfo', jsonEncode(userInfo.toJson()));

          // 启动心跳服务
          heartbeatService.startHeartbeat();

          // 跳转到主页
          if (mounted) {
            Navigator.pushReplacement(
              context,
              MaterialPageRoute(
                builder: (context) => const HomeScreen(),
              ),
            );
          }
        } else {
          if (mounted) {
            ScaffoldMessenger.of(context).showSnackBar(
              SnackBar(content: Text(response.data['msg'] ?? '登录失败')),
            );
          }
        }
      } catch (e) {
        if (mounted) {
          ScaffoldMessenger.of(context).showSnackBar(
             SnackBar(content: Text('$e')),
          );
        }
      }
    }
  }

  @override
  void dispose() {
    _employeeIdController.dispose();
    _passwordController.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      resizeToAvoidBottomInset: false,
      body: Container(
        decoration: const BoxDecoration(
          gradient: LinearGradient(
            begin: Alignment.topLeft,
            end: Alignment.bottomRight,
            colors: [
              Color(0xFFFFA726),
              Color(0xFFFF7043),
            ],
          ),
        ),
        child: SafeArea(
          child: Center(
            child: SingleChildScrollView(
              physics: const NeverScrollableScrollPhysics(),
              padding: const EdgeInsets.all(24.0),
              child: Card(
                elevation: 8,
                shape: RoundedRectangleBorder(
                  borderRadius: BorderRadius.circular(16),
                ),
                child: Padding(
                  padding: const EdgeInsets.all(24.0),
                  child: Form(
                    key: _formKey,
                    child: Column(
                      mainAxisSize: MainAxisSize.min,
                      children: [
                        const Icon(
                          Icons.local_shipping,
                          size: 80,
                          color: Colors.orange,
                        ),
                        const SizedBox(height: 16),
                        const Text(
                          '金虎送货',
                          style: TextStyle(
                            fontSize: 28,
                            fontWeight: FontWeight.bold,
                            color: Colors.orange,
                          ),
                        ),
                        const SizedBox(height: 32),
                        TextFormField(
                          controller: _employeeIdController,
                          decoration: InputDecoration(
                            labelText: '工号',
                            prefixIcon: const Icon(Icons.person),
                            border: OutlineInputBorder(
                              borderRadius: BorderRadius.circular(12),
                            ),
                          ),
                          validator: (value) {
                            if (value == null || value.isEmpty) {
                              return '请输入工号';
                            }
                            return null;
                          },
                        ),
                        const SizedBox(height: 16),
                        TextFormField(
                          controller: _passwordController,
                          obscureText: !_isPasswordVisible,
                          decoration: InputDecoration(
                            labelText: '密码',
                            prefixIcon: const Icon(Icons.lock),
                            suffixIcon: IconButton(
                              icon: Icon(
                                _isPasswordVisible
                                    ? Icons.visibility_off
                                    : Icons.visibility,
                              ),
                              onPressed: () {
                                setState(() {
                                  _isPasswordVisible = !_isPasswordVisible;
                                });
                              },
                            ),
                            border: OutlineInputBorder(
                              borderRadius: BorderRadius.circular(12),
                            ),
                          ),
                          validator: (value) {
                            if (value == null || value.isEmpty) {
                              return '请输入密码';
                            }
                            return null;
                          },
                        ),
                        const SizedBox(height: 24),
                        Padding(
                          padding: const EdgeInsets.symmetric(horizontal: 4),
                          child: Row(
                            children: [
                              Checkbox(
                                value: _autoLogin,
                                onChanged: (value) {
                                  setState(() {
                                    _autoLogin = value ?? false;
                                  });
                                },
                              ),
                              const Text('30天内自动登录'),
                              GestureDetector(
                                onTap: () {
                                  showDialog(
                                    context: context,
                                    builder: (context) => AlertDialog(
                                      title: const Text('自动登录说明'),
                                      content: const Text('开启后30天内无需重新登录，30天后需要重新输入密码'),
                                      actions: [
                                        TextButton(
                                          onPressed: () => Navigator.pop(context),
                                          child: const Text('知道了'),
                                        ),
                                      ],
                                    ),
                                  );
                                },
                                child: const Padding(
                                  padding: EdgeInsets.all(8.0),
                                  child: Icon(
                                    Icons.info_outline,
                                    size: 16,
                                    color: Colors.grey,
                                  ),
                                ),
                              ),
                            ],
                          ),
                        ),
                        const SizedBox(height: 24),
                        SizedBox(
                          width: double.infinity,
                          height: 48,
                          child: ElevatedButton(
                            onPressed: _login,
                            style: ElevatedButton.styleFrom(
                              shape: RoundedRectangleBorder(
                                borderRadius: BorderRadius.circular(12),
                              ),
                            ),
                            child: const Text(
                              '登录',
                              style: TextStyle(fontSize: 16),
                            ),
                          ),
                        ),
                        const SizedBox(height: 16),
                        // Row(
                        //   mainAxisAlignment: MainAxisAlignment.spaceBetween,
                        //   children: [
                        //     TextButton(
                        //       onPressed: () {
                        //         // TODO: 实现忘记密码逻辑
                        //       },
                        //       child: const Text('忘记密码？'),
                        //     ),
                        //     TextButton(
                        //       onPressed: () {
                        //         // TODO: 实现注册逻辑
                        //       },
                        //       child: const Text('注册账号'),
                        //     ),
                        //   ],
                        // ),
                        const SizedBox(height: 16),
                        Text(
                          'v${widget.version}',
                          style: const TextStyle(
                            color: Colors.grey,
                            fontSize: 12,
                          ),
                        ),
                      ],
                    ),
                  ),
                ),
              ),
            ),
          ),
        ),
      ),
    );
  }
} 